package com.sxt.provider.callback;

import com.sxt.commons.dto.CallbackResponse;
import com.sxt.pojo.entity.Order;
import com.sxt.provider.order.OrderService;
import com.sxt.provider.sp.SpConfigService;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Map;

@Component
public class FuhuiCallbackController {
	Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	OrderService orderService;
	@Autowired
	SpConfigService spConfigService;

	//付汇
	public CallbackResponse fuhuiCallback(Map<String, Object> params) throws Exception {
		//校验参数
		Assert.notNull(params, "接收参数为空");
		//验签
		if("1".equals(params.get("result"))){
			String tradeNo = params.get("agent_bill_id").toString();
			Order order = orderService.getByTradeNo(tradeNo);
			if(order==null) {
				logger.info("fuhuiCallback回调失败：查无此订单="+tradeNo);
				return CallbackResponse.error();
			}
			Map<String, Object> keyValues = spConfigService.getKeyValues(order.getSpId());
			String key = keyValues.get("key").toString();
			String fromSign = params.get("sign").toString();
			String signStr ="result=1&agent_id="+params.get("agent_id")+"&jnet_bill_no="+params.get("jnet_bill_no")
					+"&agent_bill_id="+params.get("agent_bill_id")+"&pay_type="+params.get("pay_type")
					+"&pay_amt="+params.get("pay_amt")+"&remark="+params.get("remark")+"&key="+key;
			String mySign = DigestUtils.md5Hex(signStr);
			if(fromSign.equals(mySign)){
				//设为成功+发送通知
				orderService.setOrderSuccess(order.getTradeNo());
				return CallbackResponse.ok();
			}else {
				logger.info("fuhuiCallback回调失败：查无此订单="+tradeNo);
			}
		}
		return CallbackResponse.error();
	}
}
